const tokenService = require('../services/tokenService');
const UserService = require('../services/user');
const Result = require('../utils/result');

module.exports = {
  // 登录方法
  async login(ctx) {
    const { nickname, phone } = ctx.request.body;
    if (!nickname || !phone) {
      ctx.body = Result.fail('nickname和phone为必填项');
      return;
    }

    // 查找用户
    const user = await UserService.login(nickname, phone);
    if (!user) {
      ctx.body = Result.unauthorized('用户不存在或信息错误');
      return;
    }

    // 生成token
    const token = tokenService.generateToken({ id: user.id, nickname: user.nickname, phone: user.phone });

    // 存储token到数据库
    await user.update({ authToken: token });

    ctx.body = Result.success({
      token,
      user: {
        id: user.id,
        nickname: user.nickname,
        phone: user.phone
      }
    }, '登录成功');
  }
};